import os
import time

def do_clear_jar(directory,file_pre,is_remove):
    if os.path.exists(directory):
        # 获取以 'bq-web-acs_' 为前缀的文件列表
        files = [f for f in os.listdir(directory) if f.endswith(file_pre)]
        # 获取每个文件的完整路径
        file_paths = [os.path.join(directory, f) for f in files]
        # 排序文件，按文件修改时间升序（最老的文件排在前面）
        file_paths.sort(key=lambda x: os.path.getmtime(x))
        # 删除除了最新两个版本外的所有文件
        for file_path in file_paths[:-2]:
            if is_remove:
                os.remove(file_path)
                print(f"已删除文件: {file_path}")
            else:
                print(f"即将删除文件: {file_path}")
    else:
        print(f"目录不存在: {directory}")

if __name__ == '__main__':
    pre_list = {"bq-service-abms","bq-service-cache","bq-service-market","bq-service-sso","bq-service-gateway",
                "bq-web-abms","bq-web-abp","bq-web-acs","bq-web-fprocess","bq-db-sync"}
    directory = '/root/java/'
    for file_pre in pre_list:
        # do_clear_jar(directory+file_pre,'.tar',False)
        do_clear_jar(directory+file_pre,'.tar',True)



